package com.test.algorithm;

import io.shardingsphere.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.Collection;

/**
 * Created by Jack on 6/30/2018.
 */
@Slf4j
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        final int modSize = availableTargetNames.size();
        String shardingKey = shardingValue.getValue().toString();
        final int shardingKeyLength = shardingKey.length();
        shardingKey = StringUtils.substring(shardingKey, shardingKeyLength - 4, shardingKeyLength);
        final String mod = String.valueOf(NumberUtils.toInt(shardingKey, 1) % modSize);
        for (String targetName : availableTargetNames) {
            if (StringUtils.endsWith(targetName, mod)) {
                log.info("Matched sharding name:{}-{}-{}", targetName, shardingKey, shardingValue.getValue());
                return targetName;
            }
        }
        return null;
    }
}
